package com.chushouya.product.service.admin.impl;

import com.chushouya.common.support.Contexts;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Beans;
import com.general.framework.core.lang.Check;
import com.general.framework.core.lang.Strings;
import com.chushouya.product.dao.entity.ProductAttrEntity;
import com.chushouya.product.dao.entity.ProductSkuEntity;
import com.chushouya.product.dao.repository.ProductSkuRepository;
import com.chushouya.product.dto.admin.productsku.ProductSkuDataDTO;
import com.chushouya.product.dto.admin.productsku.ProductSkuListDTO;
import com.chushouya.product.dto.admin.productsku.ProductSkuPriceUpdateDTO;
import com.chushouya.product.dto.admin.productsku.ProductSkuQuery;
import com.chushouya.product.dto.admin.productsku.SkuGenerateDTO;
import com.chushouya.product.dao.entity.AttributeItemValueEntity;
import com.chushouya.product.dao.repository.AttributeItemValueRepository;
import com.chushouya.product.service.admin.ProductSkuService;
import com.chushouya.product.service.admin.ProductAttrService;
import com.chushouya.product.constants.SkuGenerateConstants;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品SKU业务实现
 */
@Service
public class ProductSkuServiceImpl implements ProductSkuService {

    @Resource
    private ProductSkuRepository productSkuRepository;
    
    @Resource
    private AttributeItemValueRepository attributeItemValueRepository;
    
    @Resource
    private ProductAttrService productAttrService;

    @Override
    public void removeProductSku(Long skuId) {
        Check.notNull(skuId, "商品SKU ID不能为空");
        
        ProductSkuEntity existEntity = productSkuRepository.selectByPrimaryKey(skuId);
        Check.notNull(existEntity, "商品SKU不存在");
        
        // 逻辑删除
        ProductSkuEntity entity = new ProductSkuEntity();
        entity.setSkuId(skuId);
        entity.setDelFlag(1); // 已删除
        entity.setUpdateTime(new Date());
        
        productSkuRepository.updateByPrimaryKeySelective(entity);
    }

    @Override
    public List<ProductSkuListDTO> selectProductSkuListByProductId(Long productId) {
        Check.notNull(productId, "商品ID不能为空");
        
        ProductSkuQuery query = new ProductSkuQuery();
        query.setProductId(productId);
        
        List<ProductSkuEntity> list = productSkuRepository.selectList(query);
        return Beans.copyList(list, ProductSkuListDTO.class);
    }


    @Override
    public void clearProductSkuByProductId(Long productId) {
        Check.notNull(productId, "商品ID不能为空");
        
        productSkuRepository.deleteByProductId(productId);
    }

    @Override
    public Integer generateSkuCombinations(SkuGenerateDTO skuGenerateDTO) {
        // 1. 参数校验
        validateSkuGenerateParams(skuGenerateDTO);
        
        // 2. 清空原有数据
        clearExistingData(skuGenerateDTO.getProductId());
        
        // 3. 查询并分组属性值
        Map<Long, List<AttributeItemValueEntity>> attrGroupMap = loadAndGroupAttributeValues(skuGenerateDTO.getAttrValueList());
        
        // 4. 生成SKU组合（包含跳过选项过滤）
        List<List<AttributeItemValueEntity>> combinations = generateAndValidateCombinations(attrGroupMap);
        
        // 5. 创建并保存SKU实体
        List<ProductSkuEntity> skuEntities = createSkuEntities(skuGenerateDTO.getProductId(), combinations);
        
        // 6. 保存ProductAttr数据
        saveProductAttrData(skuGenerateDTO.getProductId(), attrGroupMap);
        
        return skuEntities.size();
    }

    /**
     * 校验SKU生成参数
     */
    private void validateSkuGenerateParams(SkuGenerateDTO skuGenerateDTO) {
        Check.notNull(skuGenerateDTO, "SKU生成参数不能为空");
        Check.notNull(skuGenerateDTO.getProductId(), "商品ID不能为空");
        Check.notEmpty(skuGenerateDTO.getAttrValueList(), "属性值ID列表不能为空");
    }

    /**
     * 清空原有数据
     */
    private void clearExistingData(Long productId) {
        productAttrService.clearProductAttrByProductId(productId);
        clearProductSkuByProductId(productId);
    }

    /**
     * 加载并分组属性值
     */
    private Map<Long, List<AttributeItemValueEntity>> loadAndGroupAttributeValues(List<Long> attrValueIds) {
        // 查询属性值信息
        List<AttributeItemValueEntity> attrValues = new ArrayList<>();
        for (Long attrValueId : attrValueIds) {
            AttributeItemValueEntity entity = attributeItemValueRepository.selectByPrimaryKey(attrValueId);
            if (entity != null) {
                attrValues.add(entity);
            }
        }
        
        if (attrValues.isEmpty()) {
            throw Ex.business("未找到有效的属性值信息");
        }

        // 按属性ID分组
        return attrValues.stream()
                .collect(Collectors.groupingBy(AttributeItemValueEntity::getAttrItemId));
    }

    /**
     * 生成并验证组合
     */
    private List<List<AttributeItemValueEntity>> generateAndValidateCombinations(Map<Long, List<AttributeItemValueEntity>> attrGroupMap) {
        // 生成所有可能的组合（在此步骤中进行isSkipOption判断）
        List<List<AttributeItemValueEntity>> combinations = generateCombinations(new ArrayList<>(attrGroupMap.values()));
        
        // 检查组合数量是否超过限制
        if (combinations.size() > SkuGenerateConstants.BatchConfig.MAX_COMBINATIONS) {
            throw new RuntimeException("生成的SKU组合数量过多(" + combinations.size() + ")，超过最大限制(" + SkuGenerateConstants.BatchConfig.MAX_COMBINATIONS + ")");
        }
        
        return combinations;
    }

    /**
     * 创建SKU实体列表
     */
    private List<ProductSkuEntity> createSkuEntities(Long productId, List<List<AttributeItemValueEntity>> combinations) {
        List<ProductSkuEntity> skuEntities = new ArrayList<>();
        Date now = new Date();
        String currentUser = Contexts.getUserContext().getUserName();
        
        // 获取当前商品已有的SKU数量，用于生成SKU编码
        List<ProductSkuEntity> existingSkus = getExistingSkus(productId);
        int skuIndex = existingSkus.size();
        
        for (List<AttributeItemValueEntity> combination : combinations) {
            skuIndex++;
            String skuCode = generateUniqueSkuCode(productId, skuIndex, existingSkus);
            
            if (skuCode != null) {
                ProductSkuEntity skuEntity = buildSkuEntity(productId, combination, skuCode, currentUser, now);
                skuEntities.add(skuEntity);
            }
        }

        // 批量插入SKU
        if (!skuEntities.isEmpty()) {
            productSkuRepository.batchInsert(skuEntities);
        }
        
        return skuEntities;
    }

    /**
     * 获取已存在的SKU列表
     */
    private List<ProductSkuEntity> getExistingSkus(Long productId) {
        ProductSkuQuery existingQuery = new ProductSkuQuery();
        existingQuery.setProductId(productId);
        return productSkuRepository.selectList(existingQuery);
    }

    /**
     * 生成唯一的SKU编码
     */
    private String generateUniqueSkuCode(Long productId, int skuIndex, List<ProductSkuEntity> existingSkus) {
        String skuCode = "sku-" + productId + "-" + skuIndex;
        
        // 检查SKU编码是否已存在
        boolean exists = existingSkus.stream().anyMatch(sku -> skuCode.equals(sku.getSkuCode()));
        return exists ? null : skuCode; // 如果存在则返回null，跳过该SKU
    }

    /**
     * 构建SKU实体
     */
    private ProductSkuEntity buildSkuEntity(Long productId, List<AttributeItemValueEntity> combination, 
                                          String skuCode, String currentUser, Date now) {
        ProductSkuEntity skuEntity = new ProductSkuEntity();
        skuEntity.setProductId(productId);
        skuEntity.setSkuCode(skuCode);
        skuEntity.setSkuAttrCode(generateSkuAttrCode(combination));
        skuEntity.setSkuName(generateSkuName(combination));
        skuEntity.setSkuData(generateSkuData(combination));
        skuEntity.setBasePrice(BigDecimal.ZERO);
        skuEntity.setMinPrice(BigDecimal.ZERO);
        skuEntity.setCalcType(1); // 默认按件数
        skuEntity.setSort(0);
        skuEntity.setStatus(1); // 默认启用
        skuEntity.setDelFlag(0); // 未删除
        skuEntity.setHandleUser(currentUser);
        skuEntity.setCreateTime(now);
        skuEntity.setUpdateTime(now);
        return skuEntity;
    }

    /**
     * 保存ProductAttr数据
     */
    private void saveProductAttrData(Long productId, Map<Long, List<AttributeItemValueEntity>> attrGroupMap) {
        if (!attrGroupMap.isEmpty()) {
            List<ProductAttrEntity> productAttrList = generateProductAttrList(productId, attrGroupMap);
            productAttrService.batchInsertProductAttrEntities(productAttrList);
        }
    }

    /**
     * 生成所有可能的属性值组合
     */
    private List<List<AttributeItemValueEntity>> generateCombinations(List<List<AttributeItemValueEntity>> attrGroups) {
        List<List<AttributeItemValueEntity>> result = new ArrayList<>();
        generateCombinationsRecursive(attrGroups, 0, new ArrayList<>(), result);
        return result;
    }

    /**
     * 递归生成组合
     */
    private void generateCombinationsRecursive(List<List<AttributeItemValueEntity>> attrGroups, 
                                             int index, 
                                             List<AttributeItemValueEntity> current, 
                                             List<List<AttributeItemValueEntity>> result) {
        if (index == attrGroups.size()) {
            // 最终检查：确保组合中没有跳过选项
            boolean hasSkipOption = current.stream()
                    .anyMatch(entity -> isSkipOption(entity.getValueContent()));
            if (!hasSkipOption) {
                result.add(new ArrayList<>(current));
            }
            return;
        }

        for (AttributeItemValueEntity attrValue : attrGroups.get(index)) {
            // 在递归前检查是否为跳过选项
            if (!isSkipOption(attrValue.getValueContent())) {
                current.add(attrValue);
                generateCombinationsRecursive(attrGroups, index + 1, current, result);
                current.remove(current.size() - 1);
            }
        }
    }


    /**
     * 生成SKU属性编码 (格式: attrId:valueId,attrId:valueId)
     */
    private String generateSkuAttrCode(List<AttributeItemValueEntity> combination) {
        return combination.stream()
                .sorted(Comparator.comparing(AttributeItemValueEntity::getAttrItemId))
                .map(attr -> attr.getAttrItemId() + ":" + attr.getAttrValueId())
                .collect(Collectors.joining(","));
    }

    /**
     * 生成SKU名称
     */
    private String generateSkuName(List<AttributeItemValueEntity> combination) {
        return combination.stream()
                .sorted(Comparator.comparing(AttributeItemValueEntity::getAttrItemId))
                .map(AttributeItemValueEntity::getValueContent)
                .collect(Collectors.joining(","));
    }

    /**
     * 生成SKU数据JSON
     */
    private String generateSkuData(List<AttributeItemValueEntity> combination) {
        try {
            List<ProductSkuDataDTO> skuDataList = combination.stream()
                    .sorted(Comparator.comparing(AttributeItemValueEntity::getAttrItemId))
                    .map(attr -> new ProductSkuDataDTO(
                            attr.getAttrItemId(),
                            attr.getAttrName(),
                            attr.getValueContent(),
                            attr.getAttrValueId()
                    ))
                    .collect(Collectors.toList());

            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsString(skuDataList);
        } catch (Exception e) {
            throw new RuntimeException("生成SKU数据JSON失败", e);
        }
    }

    /**
     * 生成ProductAttr数据列表
     */
    private List<ProductAttrEntity> generateProductAttrList(Long productId, Map<Long, List<AttributeItemValueEntity>> attrGroupMap) {
        List<ProductAttrEntity> productAttrList = new ArrayList<>();
        Date now = new Date();
        int sort = 1;
        
        for (Map.Entry<Long, List<AttributeItemValueEntity>> entry : attrGroupMap.entrySet()) {
            Long attrId = entry.getKey();
            List<AttributeItemValueEntity> attrValues = entry.getValue();
            
            if (!attrValues.isEmpty()) {
                // 获取属性名称（所有同属性ID的值应该有相同的属性名称）
                String attrName = attrValues.get(0).getAttrName();
                
                // 生成属性值JSON数组
                List<Map<String, Object>> valueList = attrValues.stream()
                        .map(attr -> {
                            Map<String, Object> valueMap = new HashMap<>();
                            valueMap.put("valueContent", attr.getValueContent());
                            valueMap.put("valueId", attr.getAttrValueId().toString());
                            return valueMap;
                        })
                        .collect(Collectors.toList());
                
                try {
                    ObjectMapper objectMapper = new ObjectMapper();
                    String attrValuesJson = objectMapper.writeValueAsString(valueList);
                    
                    ProductAttrEntity productAttr = new ProductAttrEntity();
                    productAttr.setProductId(productId);
                    productAttr.setAttrId(attrId);
                    productAttr.setAttrName(attrName);
                    productAttr.setAttrValues(attrValuesJson);
                    productAttr.setSort(sort++);
                    productAttr.setCreateTime(now);
                    
                    productAttrList.add(productAttr);
                } catch (Exception e) {
                    throw new RuntimeException("生成ProductAttr数据JSON失败", e);
                }
            }
        }
        
        return productAttrList;
    }

    /**
     * 检查是否为跳过选项
     */
    private boolean isSkipOption(String valueContent) {
        if (Strings.isEmpty(valueContent)) {
            return false;
        }
        
        // 检查是否包含跳过关键词
        return SkuGenerateConstants.SKIP_OPTIONS.stream()
                .anyMatch(skipOption -> valueContent.contains(skipOption));
    }

    @Override
    public Boolean updateSkuPrice(ProductSkuPriceUpdateDTO priceUpdateDTO) {
        Check.notNull(priceUpdateDTO, "价格更新参数不能为空");
        Check.notNull(priceUpdateDTO.getSkuId(), "SKU ID不能为空");
        
        // 检查SKU是否存在
        ProductSkuEntity existEntity = productSkuRepository.selectByPrimaryKey(priceUpdateDTO.getSkuId());
        Check.notNull(existEntity, "商品SKU不存在");
        
        // 更新价格字段
        ProductSkuEntity updateEntity = new ProductSkuEntity();
        updateEntity.setSkuId(priceUpdateDTO.getSkuId());
        
        if (priceUpdateDTO.getMinPrice() != null) {
            updateEntity.setMinPrice(priceUpdateDTO.getMinPrice());
        }
        
        if (priceUpdateDTO.getBasePrice() != null) {
            updateEntity.setBasePrice(priceUpdateDTO.getBasePrice());
        }
        
        updateEntity.setUpdateTime(new Date());
        
        return productSkuRepository.updateByPrimaryKeySelective(updateEntity) > 0;
    }
}
